'use strict';

const semver = require('semver');
const colors = require('colors');

const log = require('@dmj-cli/log');

const LOWEST_NODE_VERSION = '12.0.0';

class Command {
	constructor(argv) {
		if (!argv) {
			throw new Error('参数不能为空!');
		}
		if (!Array.isArray(argv)) {
			throw new Error('参数必须为数组!');
		}
		if (argv.length < 1) {
			throw new Error('参数列表为空!');
		}
		this._argv = argv;
		this.runner = new Promise((resolve, reject) => {
			let chain = Promise.resolve();
			chain = chain.then(() => this.checkNodeVersion());
			chain = chain.then(() => this.initArgs());
			chain = chain.then(() => this.init());
			chain = chain.then(() => this.exec());
			chain.catch(err => {
				log.error(err.message);
			})
		})
	}

	init() {
		throw new Error('init必须实现');
	}

	exec() {
		console.log('init 的业务逻辑');;
	}

	// 检查node版本号
	checkNodeVersion() {
		// 第一步获取当前的node版本号
		const currentNodeVersion = process.version;
		const lowestVersion = LOWEST_NODE_VERSION;
		// 第二步比对版本号
		if (!semver.gte(currentNodeVersion, lowestVersion)) {
			throw new Error(colors.red(`dmj-cli 需要安装 v${lowestVersion} 以上版本的Node.js`));
		}
	}

	// 初始化参数
	initArgs() {
		// 这里拼装参数数据
		this._cmd = {
			...this._argv[this._argv.length - 1],
			...this._argv[this._argv.length - 2]
		};
		this._argv = this._argv.slice(0, this._argv.length - 1)
	}
}

module.exports = Command;